package org.joy.hpc.analyzer;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Vector;

import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.joy.analyzer.Hit;

public class HitWritable implements Writable, Comparable<HitWritable>{
	private ArrayWritable pos;
	private double score;
	private Text url;

	public HitWritable(HitWritable w){
		url = new Text(w.getUrl());
		score = w.getScore();
		pos = new ArrayWritable(IntWritable.class, w.getPos());
	}
	
	public HitWritable() {
		// TODO Auto-generated constructor stub
		url = new Text();
		pos = new ArrayWritable(IntWritable.class);
	}
	public HitWritable(Hit h, String URL) {
		// TODO Auto-generated constructor stub
		Vector<IntWritable> t = new Vector<IntWritable>();
		for(int i:h.getPos()){
			t.add(new IntWritable(i));
		}
		this.pos =new ArrayWritable(IntWritable.class, t.toArray(new IntWritable[0]));
		this.url = new Text(URL);
		this.score = h.getScore();
	}
	@Override
	public void readFields(DataInput in) throws IOException {
		// TODO Auto-generated method stub
		url = new Text(in.readUTF());
		score = in.readDouble();
		pos.readFields(in);
	}

	@Override
	public void write(DataOutput out) throws IOException {
		// TODO Auto-generated method stub
		out.writeUTF(url.toString());
		out.writeDouble(score);
		pos.write(out);
	}

	public static HitWritable read(DataInput in) throws IOException{
		HitWritable t = new HitWritable();
		t.readFields(in);
		return t;
	}
	public Writable[] getPos() {
		return pos.get();
	}
	public double getScore() {
		return score;
	}
	public Text getUrl() {
		return url;
	}
	@Override
	public int compareTo(HitWritable o) {
		return Double.compare(o.getScore(),score);
	}
}
